package com.xls.commonlibrary.ad.adn.gm;

import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BN_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BN_TEST_INDEX;

import android.graphics.Point;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.orhanobut.logger.Logger;
import com.xls.commonlibrary.http.biz.CodeRewardUtil;

import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;

public class GMBannerUtil {

    //    private String mMediaId = "945493677"; // 融合广告位 demo id
    private String mMediaId = ""; // 融合广告位 正式 id    20001 拉不来广告

    // banner size 需要和GM后台配置的一致，不然有白边
    float l = 350f;// 单位px
    float w = 100f;


    private String TAG = "GMUtil";
    private boolean isAlive = true;// 是否处于生命周期可见 状态

    private static volatile GMBannerUtil singleton = null;

    private GMBannerUtil() {
    }

    public static GMBannerUtil getInstance() {
        if (singleton == null) {
            synchronized (GMBannerUtil.class) {
                if (singleton == null) {
                    singleton = new GMBannerUtil();
                }
            }
        }
        return singleton;
    }


    AppCompatActivity activity;
    ValueCallback<Boolean> valueCallback;

    public void loadBanner(@NonNull AppCompatActivity activity,
                           @NonNull FrameLayout container,
                           @NonNull ValueCallback<Boolean> valueCallback
    ) {

        this.activity = activity;
        this.valueCallback = valueCallback;
        this.mBannerContainer = container;
        Logger.d("=======showBanner=");

        addLifecycle();
        initListeners();


        loadBannerAd();

    }

    private void callbackSuccess() {
        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(true);
    }

    private void callbackFail() {
        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(false);
    }


    private void addLifecycle() {// 重要
        if (this.activity == null) return;

        this.activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            // 还有很多生命周期都可以感知
            // 这里只关注 onDestroy()的注销ad对象
            @Override
            public void onDestroy(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);
//                Logger.d("===========LifecycleOwner=========onDestroy===========");

                /** 6、在onDestroy中销毁广告 */
                if (mBannerAd != null) {
                    mBannerAd.destroy();
                }

                isAlive = false;

            }

            @Override
            public void onResume(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onResume(owner);
                isAlive = true;
            }

            @Override
            public void onPause(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onPause(owner);
                isAlive = false;
            }
        });
    }


    private TTNativeExpressAd mBannerAd; // Banner广告对象
    private TTAdNative.NativeExpressAdListener mBannerListener; // 广告加载监听器
    private TTNativeExpressAd.ExpressAdInteractionListener mBannerInteractionListener; // 广告展示监听器
    private TTAdDislike.DislikeInteractionCallback mDislikeCallback; // 接受广告关闭回调

    private FrameLayout mBannerContainer; // banner广告容器view


    private void loadBannerAd() {
        Logger.d("===========GMUtil=========isAlive===========" + isAlive);
        if (!isAlive) return;


        mMediaId = CodeRewardUtil.getInstance().getAdId(HYLC_XXL_BN_TEST, HYLC_XXL_BN_TEST_INDEX);

        /** 1、创建AdSlot对象 */
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(this.mMediaId)
                .setImageAcceptedSize(
//                        UIUtils.dp2px(this.activity, l),
                        UIUtils.getScreenWidthInPx(this.activity),

                        UIUtils.dp2px(this.activity, w)) // 单位px
                .build();

        /** 2、创建TTAdNative对象 */
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(this.activity);

        /** 3、创建加载、展示监听器 */
        initListeners();

        Logger.d("===========GMUtil=========loadBannerExpressAd===========");

        /** 4、加载广告 */
        adNativeLoader.loadBannerExpressAd(adSlot, mBannerListener);
    }

    /**
     * 5、广告加载成功后，设置监听器，展示广告
     */
    private void showBannerAdLayout() {
        if (mBannerAd != null) {
            mBannerAd.setExpressInteractionListener(mBannerInteractionListener);
            mBannerAd.setDislikeCallback(this.activity, mDislikeCallback);
            View bannerView = mBannerAd.getExpressAdView();
            if (bannerView != null && mBannerContainer != null) {
                mBannerContainer.removeAllViews();
                mBannerContainer.addView(bannerView,getUnifiedBannerLayoutParams());
            }
        } else {
            Log.d(TAG, "请先加载广告或等待广告加载完毕后再展示广告");
        }
    }
    /**     5、广告加载成功后，设置监听器，展示广告 */
    private void showBannerAd() {
        if (mBannerAd != null) {
            mBannerAd.setExpressInteractionListener(mBannerInteractionListener);
            mBannerAd.setDislikeCallback(this.activity, mDislikeCallback);
            View bannerView = mBannerAd.getExpressAdView();
            if (bannerView != null && mBannerContainer != null) {
                mBannerContainer.removeAllViews();
                mBannerContainer.addView(bannerView);
            }
        } else {
            Log.d(TAG, "请先加载广告或等待广告加载完毕后再展示广告");
        }
    }

    private void initListeners() {
        // 广告加载监听器
        this.mBannerListener = new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int i, String s) {
                Log.d(TAG, "banner load fail: errCode: " + i + ", errMsg: " + s);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                if (list != null && list.size() > 0) {
                    Log.d(TAG, "banner load success");
                    mBannerAd = list.get(0);

                    showBannerAd();

                } else {
                    Log.d(TAG, "banner load success, but list is null");
                }
            }
        };
        // 广告展示监听器
        this.mBannerInteractionListener = new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int i) {
                Log.d(TAG, "banner clicked");


                callbackSuccess();
            }

            @Override
            public void onAdShow(View view, int i) {
                Log.d(TAG, "banner showed");
            }

            @Override
            public void onRenderFail(View view, String s, int i) {
                Log.d(TAG, "banner renderFail, errCode" + i + ", errMsg: " + s);

                callbackFail();
            }

            @Override
            public void onRenderSuccess(View view, float v, float v1) {
                Log.d(TAG, "banner render success");
            }
        };
        // dislike监听器，广告关闭时会回调onSelected
        this.mDislikeCallback = new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onShow() {
            }

            @Override
            public void onSelected(int i, String s, boolean b) {
                Log.d(TAG, "banner closed");

                callbackFail();

            }

            @Override
            public void onCancel() {
            }
        };
    }
    int heightOfBannerDP = 80;// banner's高度 单位：dp


    private int dp2px(int dpValue) {
        return (int) this.activity.getResources().getDisplayMetrics().density * dpValue;
    }

    //  很重要  banner add ui适配 必备方法
    private FrameLayout.LayoutParams getUnifiedBannerLayoutParams() {
        //    推荐您将 Banner 的宽高比固定为 6.4:1 以获得最佳的广告展示效果
        float scale = 6.4F;
        Point screenSize = new Point();
        this.activity.getWindowManager().getDefaultDisplay().getSize(screenSize);
//        return new FrameLayout.LayoutParams(screenSize.x, Math.round(screenSize.x / scale));

        // 169
        // 319
        // int h = Math.round(screenSize.x / scale * 3 / 2);

        // dp 适配各种手机的高度
        int h = dp2px(heightOfBannerDP);
        Logger.d("============getUnifiedBannerLayoutParams================h:" + h);
        return new FrameLayout.LayoutParams(screenSize.x, h);
    }

}
